<?php
class Form_List extends Form_Base
{
    protected $_type;
    protected $_data;
    protected $_group_level;
    protected $_group_count;
    protected $_app_controller;

    public function __construct ($type, $pagesize, $controller)
    {
        $this->_type = $type;
        $this->_limit = $pagesize;
        $this->_data = array();
        $this->_group_level = 0;
        $this->_group_count = array();
        $this->_app_controller = $controller;
    }

    public function get_total_size ($arr_where)
    {
        $primary_key = $this->primary_key(); 
        $primary_tbl = $this->primary_table();
        $arr_order_by= $this->order_by();
 
	    $query = DB::select(array('count("*")', 'count'))
	        ->from($primary_tbl);

	    foreach ($arr_where as $w)
	    {
	        $query->where($w[0], $w[1], $w[2]);
	    }
	
	    $count = $query->execute()->get('count');

        return $count;
    }

    public function build_list ($arr_where, $page = 1)
    {
        $primary_key = $this->primary_key(); 
        $primary_tbl = $this->primary_table();
        $arr_order_by= $this->order_by();

        $page_start  = $page_limit = 0;
        if ($this->_limit > 0)
        {
            $page_limit = $this->_limit;
            $page_start = ($page - 1) * $page_limit;
        }

        $query = DB::select()
            ->from('form_list_config')
            ->where('name', '=', $this->_type)
            ->order_by('sort', 'asc')
            ->execute();

        $column_keys = array();
        foreach ($query as $rs)
        {
            $key  = $rs['column_key'];
            $name = $rs['column_name'];
            $type = $rs['type'];
            $style = $rs['inline_style'];
            $sortable = $rs['sortable'];
            $keyName = $key;

            if (preg_match('/^0\s+as\s+/', $key))
            {
                list($v, $k) = explode('as', $key);
                $v = trim($v);
                $k = trim($k);
                $key = $k;
            }

            $column_keys[$keyName] = array('key' => $key, 'name' => $name, 'type' => $type, 'style' => $style, 'sortable' => $sortable);
        }

        $select_columns = array_keys($column_keys);
        if (! in_array($primary_key, $select_columns))
            $select_columns[] = $primary_key;

        $rows   = $this->_app_controller->list_get_data($page_start, $page_limit);
        if ($rows === NULL)
        {
	        $rows   = array();
	        $query  = DB::select();
	        foreach ($select_columns as $key)
            {
                if (! preg_match('/^0\s+as\s+/', $key))
	                $query->select($key);
                else
                {
                    list($v, $k) = explode('as', $key);
                    $v = trim($v);
                    $k = trim($k);
                    $query->select(DB::expr("'$v' as '$k'"));
                }
            }
	
	        $query->from($primary_tbl);
	
	        foreach ($arr_where as $w)
	        {
	            $query->where($w[0], $w[1], $w[2]);
	        }

	
	        if ($page_limit > 0 && $page_start >= 0)
	            $query->offset($page_start)->limit($page_limit);
	            
	        $query = $query->order_by($arr_order_by[0], $arr_order_by[1])
	            ->execute();
	
	        foreach ($query as $rs)
	        {
	            $rows[] = $rs;
	        }
        }
      // foreach ($column_keys as $key => $row)
      //  {
      //   $str= $key.'-->';
      //     foreach($row as $rowkey=>$rs)
      //     {$str.=$rowkey.'=>'.$rs;}
      //     echo $str."<br>";
      // }
       // return; 
        $this->_app_controller->list_filter_data ($rows);

        $table = $this->build_table ($primary_key, $column_keys, $rows);
        
        $arrButtons = $this->_app_controller->getTopButtons();
        if (! empty($arrButtons))
        {
            $buttons = array();

            foreach ($arrButtons as $btn)
            {
                $btnLabel = Arr::get($btn, 'label', '按钮');

                $btnClick = Arr::get($btn, 'onclick', '');
                $btnOnClick = empty($btnClick) ? '' : 'onclick="'.$btnClick.'"';

                $btnLink  = Arr::get($btn, 'url');
                $btnUrl   = empty($btnLink) ? 'href="javascript:;"' : 'href="'.$btnLink.'"';

                $btnClass = Arr::get($btn, 'class');
                $btnClass = empty($btnClass) ? '' : 'class="'.$btnClass.'"';

                $buttons[] = "<a $btnUrl $btnOnClick $btnClass>$btnLabel</a>";
            }

            $buttons = implode('&nbsp;&nbsp;', $buttons);

            $buttonHtml = "<div class=\"btns\">$buttons</div>";
        }
        else if ($this->_app_controller->showTopButtons())
        {
            $button = $this->build_buttons('create');
            $buttonHtml = "<div class=\"btns\">$button</div>";
        }
        else
        {
            $buttonHtml = '';
        }
        $html  =<<<EOF
<div class="list {$this->_type}">
    $buttonHtml
    $table
</div>

EOF;
        return $html;
    }

    protected function build_table ($idKey, $column_names, $rows)
    {
        $ths = '';
        foreach ($column_names as $key => $rs)
        {
            $name = $rs['name'];
            if ($rs['sortable'])
                $ths .= "\t<th sort_order=\"desc\" sort_by=\"$key\">$name</th>\n";
            else
                $ths .= "\t<th>$name</th>\n";
        }

        if ($this->_app_controller->showListActions())
            $ths .= "\t<th>操作</th>\n";

        $head = "<tr>\n$ths</tr>\n";

        $content = '';
        foreach ($rows as $row)
        {
            $tds = '';
            $id  = Arr::get($row, $idKey, 0);
            foreach ($column_names as $rs)
            {
                $key   = $rs['key'];
                $name  = $rs['name'];
                $ctype = $rs['type'];
                $style = $rs['style'];
                $val   = Arr::get($row, $key, '');
                if ($ctype == 'datetime')
                {
                    if (is_numeric($val))
                        $val = date("Y-m-d H:i:s", $val);
                    else 
                        $val = date("Y-m-d H:i:s", strtotime($val));
                }
                else if ($ctype == 'daytime')
                {
                    if (is_numeric($val))
                        $val = date("Y-m-d H:i", $val);
                    else 
                        $val = date("Y-m-d H:i", strtotime($val));
                }
                else if ($ctype == 'date')
                {
                    if (is_numeric($val))
                        $val = date("Y-m-d", $val);
                    else 
                        $val = date("Y-m-d", strtotime($val));
                }
                else if ($key == 'created' || $key == 'changed')
                {
                    if (is_numeric($val))
                        $val = date("Y-m-d H:i:s", $val);
                }
                else if (preg_match('/^link:(.+)$/', $ctype, $m))
                {
                    $linkText = $m[1];
                    $val = '<a target="_target" href="'.$val.'">'.$linkText.'</a>';
                }
                else if ($key == 'icon' || $ctype == 'image')
                {
                    $imgs = explode('|', $val);
                    $val  = $imgs[0];
                    if (! empty($val))
                        $val = '<img src="'.$val.'" height="24px">';
                    else 
                        $val = '';
                } 
                else if ($key == 'actionType')
                {
                    switch ($val)
                    {
                        case 'app_download':
                            $x = '通知栏应用下载';
                            break;
                        case 'app_webview':
                            $x = '通知栏应用广告';
                            break;
                        case 'shortcut_download':
                            $x = '桌面图标应用下载';
                            break;
                        case 'shortcut_webview':
                            $x = '桌面图标应用广告';
                            break;
                        case 'screen_webview':
                            $x = '插屏应用广告';
                            break;
                        case 'screen_download':
                            $x = '插屏应用下载';
                            break;
                    }

                    $val = $x;
                }

                $istyle = empty($style) ? '' : 'style="'.$style.'"'; 
                $className = Form_TD::className($this->_type, $key);
                $className = empty($className) ? '' : ' class="'.$className.'" ';
                $tds .= "\t<td $istyle $className>$val</td>\n";
            }

            if ($this->_app_controller->showListActions())
            {
                $opts = $this->build_action_list($id, $row);
                $tds .= "\t<td>$opts</td>\n";
            }

            $trClass = $this->_app_controller->classname_by_list_row($row);
            if ($trClass)
                $tr = "<tr class=\"$trClass\">$tds</tr>\n";
            else
                $tr = "<tr>$tds</tr>\n";
            $content .= $tr;
        }

        $table =<<<EOF
<table class="gridtable">
    $head
    $content
</table>

EOF;

        return $table;
    }

    protected function build_action_list ($id, $row)
    {
        $controller = Request::initial()->controller();
        $directory  = Request::initial()->directory();

        $directory  = empty($directory) ? '' : '/'.$directory;
        $query = $_SERVER['QUERY_STRING'];
        $query = empty($query) ? '' : '?'.$query;

        $url = "$directory/$controller/detail/$id$query";
        $detail = "<a href=\"$url\">查看</a>";

        $url = "$directory/$controller/update/$id$query";
        $update = "<a href=\"$url\">修改</a>";

        $url = "$directory/$controller/delete/$id$query";
        $delete = "<a href=\"$url\" onclick=\"return confirm('确认要删除吗')\">删除</a>";


        $menus = array();
        $menus[] = $detail;
        $menus[] = $update;
        $menus[] = $delete;

        $this->_app_controller->actions_by_list_row($row, $menus);

        return implode("|", $menus);
    }
}
